<template>
  <view style="width: 100%;height: 100%;">
    <view class="root" :style="{display: !visibleCamera ? 'flex': 'none'}">
      <view class="content">
        <uni-forms ref="formRef" :model="form" validateTrigger="blur" label-position="top" label-width="100%"
          err-show-type="toast">
          <view class="content-wrapper">
            <yy-title title="维修汽车信息"></yy-title>
            <view class="content-inner-wrapper">
              <uni-forms-item label="送修原因:" name="faultDescribe" required key="faultDescribe">
                <view class="form-content-item" :class="form.faultDescribe ?  '' : 'input-item'">
                  <uni-easyinput type="text" v-model="form.faultDescribe" :inputBorder="false" placeholder="请填写"
                    :clearable="true" />
                </view>
              </uni-forms-item>
              <view class="car-num-wrapper">
                <u-checkbox-group @change="checkboxChange">
                  <u-checkbox label="无牌车辆" v-model="form.hasCarNumber" name="true" label-color="#666666"
                    label-size="30rpx"></u-checkbox>
                </u-checkbox-group>
                <uni-forms-item label="车牌号:" name="carNumber" required key="carNumber" v-if="form.hasCarNumber == 0">
                  <view class="form-content-item" :class="form.carNumber ?  '' : 'input-item'" @click="handleShowCar">
                    <uni-easyinput type="text" v-model="form.carNumber" :inputBorder="false" placeholder="请填写" disabled
                      :clearable="true" />
                    <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                  </view>
                </uni-forms-item>
              </view>
              <uni-forms-item label="车辆颜色:" name="carColor" required key="carColor">
                <view class="form-content-item" :class="form.carColor ?  '' : 'input-item'"
                  @click="hadleShowPicker('car_color', 'carColor')">
                  <uni-easyinput type="text" v-model="form.carColor_text" :disabled="true" :inputBorder="false"
                    placeholder="请选择" :clearable="false" />
                  <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                </view>
              </uni-forms-item>
              <uni-forms-item label="车架号:" name="frameNumber" key="frameNumber">
                <view class="form-content-item" :class="form.frameNumber ?  '' : 'input-item'">
                  <uni-easyinput type="text" v-model="form.frameNumber" :inputBorder="false" placeholder="请填写"
                    :clearable="true" maxlength="30" />
                </view>
              </uni-forms-item>
              <uni-forms-item label="发动机编号:" name="engineNumber;" key="engineNumber;">
                <view class="form-content-item" :class="form.engineNumber ?  '' : 'input-item'">
                  <uni-easyinput type="text" v-model="form.engineNumber" :inputBorder="false" placeholder="请填写"
                    :clearable="true" maxlength="30" />
                </view>
              </uni-forms-item>
              <uni-forms-item label="是否可疑车辆:" name="isSuspectedVehicle" required key="isSuspectedVehicle">
                <view class="form-content-item" :class="form.isSuspectedVehicle ?  '' : 'input-item'"
                  @click="hadleShowPicker('flag_type', 'isSuspectedVehicle')">
                  <uni-easyinput type="text" v-model="form.isSuspectedVehicle_text" :inputBorder="false"
                    placeholder="请选择" :clearable="false" disabled />
                  <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
                </view>
              </uni-forms-item>
              <uni-forms-item label="车辆图片: 最多可上传3张图片，非必填）" name="imageListUrl" style="margin-bottom: 0;">
                <u-upload :fileList="form.imageListUrl" @afterRead="(info) => afterReadFive(info, 'form', 69)"
                  @delete="(info) => deletePhoto(info, 'form')" name="imageListUrl" :maxCount="3" :multiple="true"
                  width="96" height="80">
                  <image :src="baseImgUrl + 'upload-icon3.png'" style="width: 200rpx; height: 160rpx"></image>
                </u-upload>
              </uni-forms-item>
              <uni-forms-item label="送修时间:" name="sendRepairTime" required key="sendRepairTime">
                <view class="form-content-item" :class="form.sendRepairTime ?  '' : 'input-item'">
                  <uni-datetime-picker v-model="form.sendRepairTime" type="datetime" :hide-second="true"
                    :start="startTime" :end="endTime">
                    <uni-easyinput type="text" v-model="form.sendRepairTime" :inputBorder="false" placeholder="请选择"
                      :clearable="true" disabled />
                  </uni-datetime-picker>
                  <image :src="baseImgUrl + 'day-icon2.png'" style="width: 30rpx;height: 30rpx;padding:0 10rpx;">
                </view>
              </uni-forms-item>
            </view>
          </view>
          <view class="content-wrapper">
            <yy-title title="送修人员信息"></yy-title>
            <uni-forms-item label="身份证号:" name="sendRepairIdcard" required key="sendRepairIdcard">
              <view class="form-content-item" :class="form.sendRepairIdcard ?  '' : 'input-item'">
                <uni-easyinput type="idcard" :maxlength="18" v-model="form.sendRepairIdcard" :inputBorder="false"
                  placeholder="请填写" :clearable="true" />
                <u-icon slot="right" size="21" name="scan" color="#2488F5" @click="handleCamera"></u-icon>
              </view>
            </uni-forms-item>
            <uni-forms-item label="姓名:" name="sendRepairName" key="sendRepairName">
              <view class="form-content-item" :class="form.sendRepairName ?  '' : 'input-item'">
                <uni-easyinput type="text" v-model="form.sendRepairName" :inputBorder="false" placeholder="请填写"
                  :clearable="true" />
              </view>
            </uni-forms-item>
            <uni-forms-item label="手机号码:" name="sendRepairPhone" key="sendRepairPhone">
              <view class="form-content-item" :class="form.sendRepairPhone ?  '' : 'input-item'">
                <uni-easyinput type="number" :maxlength="11" v-model="form.sendRepairPhone" :inputBorder="false"
                  placeholder="请填写" :clearable="true" />
              </view>
            </uni-forms-item>
          </view>
        </uni-forms>
      </view>
      <view class="bottom">
        <yy-button-submit @submit="onSubmit"></yy-button-submit>
      </view>
    </view>
    <u-keyboard @backspace="backspace" autoChange safeAreaInsetBottom @cancel="showKeyBoard = false"
      @confirm="showKeyBoard = false" ref="uKeyboard" mode="car" :show="showKeyBoard" @change="valChange"></u-keyboard>
    <yy-photo-mask :visible.sync="visibleCamera" :baseImgUrl="baseImgUrl" :clientId="clientId"
      :clientSecret="clientSecret" @parsedSuccess="onParsedSuccess"></yy-photo-mask>
    <u-picker closeOnClickOverlay v-if="pickerShow" :show="pickerShow" :columns="pickerData" keyName="text"
      @confirm="onPickerConfirm" @cancel="pickerShow = false" @close="pickerShow = false"
      :defaultIndex="defaultIndex"></u-picker>
  </view>
</template>

<script>
  import _ from '@/utils/lodash.js'
  import uploadFileMixin from '../../../utils/upload-file-mixin'
  import pickerMixin from "@/utils/picker-mixin";

  import {
    Toast,
    checkCarNumber,
    generateUrlOptions,
    getEndOfTodayTimestamp,
    getOptionsParams,
    getTimestampDaysAgo,
    idCardRule,
    isLoading,
    navBack,
    phoneRule,
    requireInputRule
  } from '../../../utils/util'

  import {
    addPawnRecordDetails
  } from '../../../api/api'

  import moment from '../../../utils/moment'
  import {
    maintenanceRecordsAdd
  } from '../../../api/myself';

  export default {
    mixins: [uploadFileMixin, pickerMixin],
    data() {
      return {
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        baseImgUrl: this.$baseImgUrl,
        routerParams: {},
        formRef: null,
        form: this.initForm(),
        startTime: getTimestampDaysAgo(5),
        endTime: getEndOfTodayTimestamp(),
        rules: {
          faultDescribe: {
            rules: [...requireInputRule('请填写送修原因！')]
          },
          // hasCarNumber: {
          //   rules: [{
          //     required: true,
          //     errorMessage: "请选择是否有车牌！",
          //   }]
          // },
          carNumber: {
            rules: [...requireInputRule('请填写车牌号！'), {
              validateFunction: function(rule, value, data, callback) {
                if (!checkCarNumber(value)) {
                  callback('车牌号校验失败，请检查！')
                }
              }
            }]
          },
          carColor: {
            rules: [{
              required: true,
              errorMessage: "请选择车辆颜色！",
            }]
          },
          isSuspectedVehicle: {
            rules: [{
              required: true,
              errorMessage: "请选择是否可疑车辆！",
            }]
          },
          imageListUrl: {
            rules: [{
              required: false,
              errorMessage: "请上传图片证据！",
            }]
          },
          sendRepairTime: {
            rules: [{
              required: true,
              errorMessage: "请选择送修时间！",
            }]
          },
          sendRepairIdcard: {
            rules: [...requireInputRule('请填写身份证号！'), ...idCardRule()]
          },
          sendRepairPhone: {
            rules: [...phoneRule(false)]
          }
        },
        visibleCamera: false,
        uKeyboard: null,
        showKeyBoard: false,
      }
    },
    onLoad(options) {
      this.routerParams = getOptionsParams(options)
    },
    onReady() {
      this.$refs.formRef.setRules(this.rules)
    },
    methods: {
      initForm() {
        return {
          faultDescribe: '',
          hasCarNumber: '0',
          carNumber: '',
          carColor: '',
          frameNumber: '',
          engineNumber: '',
          isSuspectedVehicle: '',
          imageListUrl: [],

          // 送修人
          sendRepairTime: '',
          sendRepairName: '',
          sendRepairIdcard: '',
          sendRepairPhone: '',
        }
      },
      onSubmit() {
        this.$refs.formRef.validate().then(() => {
            let data = {
              companyMessageId: this.routerParams.companyMessageId,
              ...this.form,
              sendRepairTime: this.form.sendRepairTime ? moment(this.form
                .sendRepairTime).format('YYYY/MM/DD HH:mm:ss') : '',
              carType: 1
            };
            if (data.imageListUrl) {
              data.imageListUrl = data.imageListUrl.map(item => {
                return item.halfPath
              })
            }
            isLoading(true)
            maintenanceRecordsAdd(data).then((res) => {
                if (res.code == 200) {
                  Toast(res.message);
                  uni.$emit('add-vehicle-maintenance-success')
                  setTimeout(() => {
                    navBack();
                  }, 100)
                }
              })
              .finally(() => {
                isLoading(false)
              })
          })
          .catch(() => {})

      },
      handleAddPawn() {
        this.visiblePawn = true
      },
      handleCancelPawn() {
        this.visiblePawn = false
      },
      open() {

      },
      close() {

      },
      handleTime(val) {
        if (val) {
          this.form.pawnStartTime = val[0]
          this.form.pawnEndTime = val[1]
        }
      },
      hadleShowPicker(dictName, formKey, formName = 'form') {
        // 如果选当前选择的是 是否可疑车辆，如果没有车牌则直接 return 
        if (formKey === 'isSuspectedVehicle') {
          if (this.form.hasCarNumber == 1) {
            return
          }
        }
        this.pickerWithFormKey = formKey;
        this.pickerData[0] = this.dictMapping[dictName] || [];
        let index = this.pickerData[0].findIndex(item => item.value == this[formName][formKey])
        if (~index) {
          this.defaultIndex = [index]
        } else {
          this.defaultIndex = [0]
        }
        this.pickerShow = true;
      },
      onPickerConfirm(data, formName = 'form') {
        let {
          value,
          text
        } = data.value[0];
        this[formName][this.pickerWithFormKey] = value;
        this.$set(this[formName], `${this.pickerWithFormKey}_text`, text);
        this.pickerShow = false;
      },
      handleCamera() {
        this.visibleCamera = true;
      },
      onParsedSuccess(value) {
        const {
          domicileAddress,
          userName,
          idcard,
          nation
        } = value;
        this.$set(this.form, "sendRepairName", userName);
        this.$set(this.form, "sendRepairIdcard", idcard);
        this.visibleCamera = false;
      },
      checkboxChange(n) {
        console.log(n)
        // 无车牌
        // 判断如果没有车牌则 为可疑车辆
        const formName = 'form'
        if (n.length) {
          this.form.hasCarNumber = '1'
          this.$set(this[formName], `isSuspectedVehicle`, 1);
          this.$set(this[formName], `isSuspectedVehicle_text`, '是');
          // 清理掉车牌号
          this.$set(this[formName], 'carNumber', '')
        } else {
          this.form.hasCarNumber = '0'
          this.$set(this[formName], `isSuspectedVehicle`, 0);
          this.$set(this[formName], `isSuspectedVehicle_text`, '否');
        }
      },
      handleShowCar() {
        this.showKeyBoard = true
      },
      // 按键被点击(点击退格键不会触发此事件)
      valChange(val) {
        // 将每次按键的值拼接到value变量中，注意+=写法
        // 校验成功就不让输入了
        if (this.form.carNumber.length >= 8) {
          Toast('车牌号最多输入8位！')
          return
        }
        this.form.carNumber += val;
        console.log(this.form.carNumber);
      },
      // 退格键被点击
      backspace() {
        // 删除value的最后一个字符
        if (this.form.carNumber.length) {
          this.form.carNumber = this.form.carNumber.substr(0, this.form
            .carNumber.length - 1)
          if (this.form.carNumber.length === 0) {
            // 没有 length 的时候
            // 切换成中文
            this.$refs.uKeyboard.$children[0].$children[2].abc = false
          }
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import '../../../styles/uni-form-label-top.scss';

  .root {
    display: flex;
    width: 100%;
    height: 100%;
    flex-direction: column;
    background: #F9F9F9;

    .content {
      flex: 1;
      height: 0;
      overflow: auto;

      .content-wrapper {
        background: #FFFFFF;
        box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(207, 207, 207, 0.1608);
        border-radius: 8rpx 8rpx 8rpx 8rpx;
        padding: 40rpx 20rpx;
        margin-bottom: 10rpx;

        .car-num-wrapper {
          position: relative;

          /deep/.u-checkbox {
            position: absolute;
            right: 20rpx;
            height: 28px;
            z-index: 10;
          }

          /deep/.u-checkbox__icon-wrap {
            width: 24rpx !important;
            height: 24rpx !important;
          }
        }
      }

      .pawn-list-wrapper {
        background: #F9F9F9;
        padding: 25rpx;
        margin-bottom: 10rpx;

        .title-name {
          display: flex;
          justify-content: space-between;
          margin-bottom: 23rpx;

          .name-i {
            font-weight: bold;
            font-size: 32rpx;
            color: #181818;
          }

          .delete-i {
            display: flex;
            align-items: center;
            font-weight: 500;
            font-size: 26rpx;
            color: #F94A4A;

            .text-delete {
              margin-left: 10rpx;
            }
          }
        }

        .i-item {
          margin-bottom: 15rpx;
          display: flex;

          .i-label {
            font-weight: 500;
            font-size: 28rpx;
            color: #999999;
            width: 119rpx;
            margin-right: 16rpx;
            position: relative;
            text-align: justify;
            text-align-last: justify;
            flex-shrink: 0;



            &::after {
              content: ':';
              position: absolute;
              right: -8rpx;
            }
          }

          .i-value {
            font-weight: bold;
            font-size: 28rpx;
            color: #101010;
          }

        }
      }

      .datetime-picker-wrapper {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .text-t {
          font-weight: 500;
          font-size: 30rpx;
          color: #666666;
        }

        .t-item {
          font-weight: 400;
          font-size: 28rpx;
          color: #A2A2A2;
          width: 304rpx;
          height: 70rpx;
          background: #F9F9F9;
          border-radius: 8rpx 8rpx 8rpx 8rpx;
          border: 1rpx solid #F1EEEE;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .has-value {
          font-weight: bold;
          font-size: 30rpx;
          color: #181818;
        }
      }
    }
  }


  .tenant-info-wrapper {
    height: 80vh;
    display: flex;
    flex-direction: column;
    padding-top: 30rpx;

    .top-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 134rpx;
      padding: 0 18rpx;


      .p-title {
        font-weight: bold;
        font-size: 30rpx;
        color: #101010;
      }

      .p-cancel {
        font-weight: 500;
        font-size: 28rpx;
        color: #666666;
      }
    }

    .popup-form-wrapper {
      flex: 1;
      overflow: auto;
      height: 0;
    }

    .submit-tenant-info {
      margin-bottom: 17rpx;
      width: 680rpx;
      height: 88rpx;
      background: #2488F5;
      border-radius: 44rpx 44rpx 44rpx 44rpx;
      border: 1rpx solid #ACCBEC;
      font-weight: 500;
      font-size: 36rpx;
      color: #F9F9F9;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 85rpx;
    }
  }
</style>